package com.shijiu.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shijiu.annotation.RepeatSubmit;
import com.shijiu.common.Result;
import com.shijiu.common.ResultTest;
import com.shijiu.dao.mapper.UploaderMapper;
import com.shijiu.dto.FileChunkDTO;
import com.shijiu.dto.FileChunkResultDTO;
import com.shijiu.pojo.Uploader;
import com.shijiu.service.IUploadService;
import com.shijiu.vo.PageParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @ProjectName UploaderController
 * @author Administrator
 * @version 1.0.0
 * @Description 附件分片上传
 * @createTime 2022/4/13 0013 15:58
 */
@RestController
@RequestMapping("upload")
public class UploaderController {

   @Resource
   private IUploadService uploadService;

   @Resource
   private UploaderMapper uploaderMapper;

   @PostMapping("selectALL")
   public Result selectALL(@RequestBody PageParams pageParams) {
      return uploadService.queryFileList(pageParams);
   }

   @ApiOperation("根据id")
   @RepeatSubmit(interval = 2000, message = "接口请求过于频繁")
   @PostMapping("remove")
   public Result removeFood(@RequestBody Uploader uploader){
      if (StrUtil.isBlank(uploader.getId())){
         return Result.fail(500,"id不能为空");
      }
      return Result.success(uploaderMapper.deleteById(uploader.getId()));
   }
   /**
    * 检查分片是否存在
    *
    * @return
    */
   @GetMapping("chunk")
   public ResultTest checkChunkExist(FileChunkDTO chunkDTO) {
      FileChunkResultDTO fileChunkCheckDTO;
      try {
         fileChunkCheckDTO = uploadService.checkChunkExist(chunkDTO);
         return ResultTest.ok(fileChunkCheckDTO);
      } catch (Exception e) {
         return ResultTest.fail(e.getMessage());
      }
   }


   /**
    * 上传文件分片
    *
    * @param chunkDTO
    * @return
    */
   @PostMapping("chunk")
   public ResultTest uploadChunk(FileChunkDTO chunkDTO) {
      try {
         uploadService.uploadChunk(chunkDTO);
         return ResultTest.ok(chunkDTO.getIdentifier());
      } catch (Exception e) {
         return ResultTest.fail(e.getMessage());
      }
   }

   /**
    * 请求合并文件分片
    *
    * @param chunkDTO
    * @return
    */
   @PostMapping("merge")
   public ResultTest mergeChunks(@RequestBody FileChunkDTO chunkDTO) {
      try {
         boolean success = uploadService.mergeChunk(chunkDTO.getIdentifier(), chunkDTO.getFilename(), chunkDTO.getTotalChunks());
         return ResultTest.ok(success);
      } catch (Exception e) {
         return ResultTest.fail(e.getMessage());
      }
   }

}
